from sqlalchemy.orm import Session
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
import requests

Base = declarative_base()

class FiveMediaInfo(Base):
    __tablename__ = 'five_media_info'

    id = Column(Integer, primary_key=True)
    stream_url = Column(String)

class FPageInfo(Base):
    __tablename__ = 'f_page_info'

    id = Column(Integer, primary_key=True)
    media_id = Column(Integer, ForeignKey('five_media_info.id'))
    object_type = Column(String)
    type = Column(Integer)
    status_id = Column(Integer)
    five_media_info = relationship("FiveMediaInfo")

class FiveUrlStruct(Base):
    __tablename__ = 'five_url_struct'

    id = Column(Integer, primary_key=True)
    page_id = Column(Integer, ForeignKey('f_page_info.id'))
    short_url = Column(String)
    status_id = Column(Integer)
    url_type = Column(Integer)
    object_type = Column(String)

def insert_page_info_by_file_name(video_bytes, file_name, status_id, width, height):
    storage = build()  # Assuming build() is a function that returns a storage service
    if storage is None:
        raise Exception("获取oss上传工具失败~！")

    try:
        video = storage.upload(video_bytes, "video", file_name.split('.')[-1])
        five_media_info = FiveMediaInfo(stream_url=video)
        session.add(five_media_info)
        session.commit()

        f_page_info = FPageInfo(media_id=five_media_info.id, object_type="video", type=11, status_id=status_id, five_media_info=five_media_info)
        session.add(f_page_info)
        session.commit()

        url_struct = FiveUrlStruct(page_id=f_page_info.id, short_url=five_media_info.stream_url, status_id=f_page_info.status_id, url_type=39, object_type="video")
        session.add(url_struct)
        session.commit()

        return f_page_info
    except Exception as e:
        print(f"page info 信息插入失败~！ {file_name}", e)
        raise Exception(f"page info 信息插入失败~！ {file_name}") from e

engine = create_engine('sqlite:///:memory:')  # Use your own database URL
Session = sessionmaker(bind=engine)
session = Session()

Base.metadata.create_all(engine)